package com.core.system.controller;

import com.core.system.service.ISystemUserService;
import com.pojo.entity.SystemUserEntity;
import com.pojo.resp.user.UserInfo;
import com.utility.result.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.AccessTokenConverter;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 外部访问控制器
 * 用于解析用户信息Controller
 */
@RestController
@RequestMapping("/common/userAnalysis")
public class UserAnalysisController {

    private ResourceServerTokenServices resourceServerTokenServices;

    private AccessTokenConverter accessTokenConverter;

    private ISystemUserService userService;

    public UserAnalysisController(ResourceServerTokenServices resourceServerTokenServices,
                                  AccessTokenConverter accessTokenConverter,
                                  ISystemUserService userService) {

        this.resourceServerTokenServices = resourceServerTokenServices;
        this.accessTokenConverter = accessTokenConverter;
        this.userService = userService;
    }

    /**
     * 外部接口
     * 根据token 获取用户信息接口
     * @param token
     * @return
     */
    @GetMapping("userInfo")
    public Result<UserInfo> userInfo(@RequestParam("token") String token){
        OAuth2AccessToken oAuth2AccessToken = resourceServerTokenServices.readAccessToken(token);
        if (oAuth2AccessToken == null) {
            throw new InvalidTokenException("Token was not recognised");
        }

        if (oAuth2AccessToken.isExpired()) {
            throw new InvalidTokenException("Token has expired");
        }

        OAuth2Authentication authentication = resourceServerTokenServices.loadAuthentication(oAuth2AccessToken.getValue());

        Map<String, Object> response = (Map<String, Object>)accessTokenConverter.convertAccessToken(oAuth2AccessToken, authentication);
        String userName = (String)response.get("user_name");
        SystemUserEntity user = userService.getUser(userName);
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(user,userInfo);
        return new Result<UserInfo>(userInfo);
    }
}
